package NG::Gen::AuthCgi;
use strict;
use warnings;
use utf8;

use base 'NG::Sys::Loop::Cgi';

#sub on_init_process {
#	my ($app) = @_;
#	my ($form) = $app->SUPER::on_init_process;
#	$app->check_user($form);
#	return ($form);
#}

sub current_user {
	my $self = shift;
	my $form = shift;
	unless(exists $form->{user}){
		$self->check_user($form);
	}
	return $form->{user};
}
sub check_user {
	my $self = shift;
	my $form = shift;
	
	$form->{user} = undef;
	my $cn = $self->{cfg}{cookie_name};
	
	if((my $ses = $form->cookie($cn->{session})) && (my $id = $form->cookie($cn->{id}))){
		my $user = $self->users->get_by_id($id);
		if($user->check_session($ses)){
			$form->{user} = $user;
			if($form->{input}{vk} && $form->{input}{vk} == $user->vk){
				$form->{user_is_valid} = 1;
			}
		}
	}
	return $form->{user};
}

sub enter_user {
	my $self = shift;
	my $form = shift;
	my $user = shift;
	my $type = shift;

	my $cn = $self->{cfg}{cookie_name};
	my $ses = $user->enter_user($type,$form->{ip});
	$form->add_cookie(
		-name => $cn->{session},
		-value => $ses,
	);
	$form->add_cookie(
		-name => $cn->{id},
		-value => $user->obj_id,
		#-expires => "+1y",
	);
}

sub exit_user {
	my $self = shift;
	my $form = shift;
	if(my $user = $form->{user}){
		$user->exit_user;
	
		my $cn = $self->{cfg}{cookie_name};
		$form->add_cookie(
			-name => $cn->{session},
			-value => "",
			-expires => "-1y",
		);
	}
}

1;
